package com.infomanage.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.infomanage.bean.FieldBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.exception.DaoException;
import com.infomanage.po.Department;
import com.infomanage.po.HibernateSessionFactory;
import com.infomanage.po.LeaderreservePlan;
import com.infomanage.po.Person;
import com.infomanage.vo.LeaderreservePlanItem;

public class LeaderreservePlanDAO extends BaseDAO<LeaderreservePlan> {
	public LeaderreservePlanItem find(int id) throws DaoException{
		try {
			SearchBean searchBean  = new SearchBean();
			FieldBean fieldBean  = new FieldBean();
			fieldBean.setName("leaderReservePlanId");
			fieldBean.setValue(id);
			searchBean.add(fieldBean);
			List result = super.findByFields(new Class[] {Person.class, Department.class },
					LeaderreservePlan.class, new String[] {"personId", "deptId"},
					new String[] {"personId", "deptId"}, searchBean);
			List<LeaderreservePlanItem> items = parseResult(result);
			return items.size() == 0 ? null : items.get(0);
		} catch (Exception e) {
			throw new DaoException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}
	@SuppressWarnings("unchecked")
	public List<LeaderreservePlanItem> findAll() throws DaoException {
		try {
			List result = findAllMutilTable(new Class[] {Person.class, Department.class },
					LeaderreservePlan.class, new String[] {"personId", "deptId"},
					new String[] {"personId", "deptId"});
			return parseResult(result);
		} catch (Exception e) {
			throw new DaoException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<LeaderreservePlanItem> findByFields(SearchBean searchBean) throws DaoException {
		List result = super.findByFields(new Class[] {Person.class, Department.class },
				LeaderreservePlan.class, new String[] {"personId", "deptId"},
				new String[] {"personId", "deptId"}, searchBean);
		return parseResult(result);
	}
	
	public List<LeaderreservePlanItem> parseResult(List result){
		Iterator it = result.iterator();
		List<LeaderreservePlanItem> list = new ArrayList<LeaderreservePlanItem>();
		while (it.hasNext()) {
			Object[] o = (Object[]) it.next();
			LeaderreservePlan plan = (LeaderreservePlan) o[0];
			Person person = (Person) o[1];
			LeaderreservePlanItem item = new LeaderreservePlanItem();
			item.setBean(plan);
			item.setPerson(person);
			list.add(item);
		}
		return list;
	}

	public int count(SearchBean searchBean){
		return super.count(new Class[] {Person.class, Department.class },
				LeaderreservePlan.class, new String[] {"personId", "deptId"},
				new String[] {"personId", "deptId"}, searchBean);
	}
}
